<template>
  <LabelPrefixWraper
    v-show="mappingProps.visible"
    :class="['t-input-label', 'no-outline']"
    :required="mappingProps.required"
    :label="mappingProps.labelText"
    :hideLabel="mappingProps.hideLabel"
    :labelPosition="labelPosition"
    :helpConf="mappingProps.helpConf"
    :helpTooltip="mappingProps.helpTooltip"
    :helpPlacement="mappingProps.helpPlacement"
    :helpMore="mappingProps.helpMore"
    :helpMorePopup="mappingProps.helpMorePopup"
    :helpMoreLink="mappingProps.helpMoreLink"
    :helpMoreLinkHrefStatic="mappingProps.helpMoreLinkHrefStatic"
    :helpMoreLinkHrefExp="mappingProps.helpMoreLinkHrefExp"
    :style="mappingProps.hideLabel ? '' : 'width: auto'"
    tabindex="-1"
  >
    <Component
      ref="refComponent"
      :class="{
        'tr-buttondrop': true,
        'no-outline': true,
        'tr-buttondrop-default': !mappingProps.disable,
        'tr-buttondrop-default-disabled': mappingProps.disable,
        'tbtndrop-no-wrap': true,
        'tbtndrop-justify-between': !mappingProps.split,
        'tr-button-group-item-text': mappingProps.hideBorder,
        'tr-button-group-text': mappingProps.hideBorder,
        'tr-button-group-item-default':
          !mappingProps.hideBorder && !mappingProps.disable,
        'tr-buttondrop-notext': mappingProps.popover,
      }"
      :title="
        mappingProps.maxWidth != '' || mappingProps.maxWidth != ''
          ? mappingProps.label
          : ''
      "
      v-bind="{
        ...attrs,
        ...pickOwnForBasicComponent(mappingProps, Component.props, attrs),
      }"
      @Click="onClickHandler(mappingProps.label)"
      :style="outWidth"
    >
      <template v-slot:default>
        <List
          :class="{
            'tr-drop-btn-list': true,
            'tr-drop-btn-list-fixed': mappingProps.dropdownWidth == 'fixed',
          }"
          v-if="mappingProps.staticItems && mappingProps.staticItems.length > 0"
          :style="mappingProps.dropdownWidth == 'fixed' ? widthModel : ''"
        >
          <Item
            clickable
            v-for="(item, index) in staticItemsNew"
            :key="index"
            @click="itemClick(item, $event)"
            v-show="item.visible === false ? false : true"
            :disable="item.disabled"
            :tabIndex="attrs.tabIndex == undefined ? 1 : attrs.tabIndex"
          >
            <ItemSection avatar v-if="item.icon">
              <Icon :name="item.icon"></Icon>
            </ItemSection>
            <ItemSection
              no-wrap
              :style="item.icon ? '' : 'align-items: center;text-align:center;'"
            >
              <ItemLabel
                class="item-section-no-wrap"
                :title="item.hint ?? item.label"
              >
                {{ item.showIcon ? '' : item.label }}
              </ItemLabel>
            </ItemSection>
          </Item>
        </List>
        <slot v-else name="default"></slot>
      </template>
      <template v-slot:label>
        <slot name="label"></slot>
      </template>
      <template v-slot:loading>
        <slot name="loading"></slot>
      </template>
    </Component>
  </LabelPrefixWraper>
</template>
<script>
import { useQuasar } from '@teld/q-components';
import { cloneDeep } from 'lodash';
import Component from '@teld/q-components/ButtonDropdown';
import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent,
} from 't/common/utils';
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  ref,
  toRaw,
  watch,
} from 'vue';
import Icon from '../icon';
import Item from '../item';
import ItemLabel from '../item-label';
import ItemSection from '../item-section';
import LabelPrefixWraper from '../label-prefix-wraper';
import List from '../list';
import styles from './index.module.scss';
import './index.scss';

export * from '@teld/q-components/ButtonDropdown';

export default defineComponent({
  name: fixNameSpace(Component.name),
  props: {
    ...commonProps,
    ...Component.props,
    ...LabelPrefixWraper.props,
    staticItems: {
      type: Array,
      default() {
        return [];
      },
    },
    autoClose: {
      type: Boolean,
      default() {
        return true;
      },
    },
    popover: {
      type: Boolean,
      default() {
        return false;
      },
    },
    showModel: {
      type: String,
      default() {
        return 'auto';
      },
    },
    maxWidth: {
      type: String,
      default() {
        return '';
      },
    },
    fixedWidth: {
      type: String,
      default() {
        return '';
      },
    },
    labelText: {
      type: String,
      default() {
        return '';
      },
    },
    dropdownWidth: {
      type: String,
      default() {
        return 'auto';
      },
    },
    ripple: {
      type: [Boolean, Object],
      default() {
        return false;
      },
    },
    hideBorder: {
      type: Boolean,
      default() {
        return false;
      },
    },
    disable: {
      type: Boolean,
      default() {
        return false;
      },
    },
    needWatchStaticItems: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  emits: ['dropdown-item-click'],
  components: {
    Component,
    LabelPrefixWraper,
    List,
    Icon,
    Item,
    ItemSection,
    ItemLabel,
  },
  setup(props, { attrs, emit, expose, slots }) {
    const $q = useQuasar();
    const refComponent = ref();
    let widthModel = ref('');
    const [mappingProps, mappingExpose] = useMappingProps(props, {
      show() {
        refComponent.value.show(...arguments);
      },
      hide() {
        refComponent.value.hide(...arguments);
      },
      toggle() {
        refComponent.value.toggle(...arguments);
      },
      setBtnDropDisableByIndex(index, val) {
        staticItemsNew.value[index].disabled = val;
        labelChange(index);
      },
      setBtnDropVisibleByIndex(index, val) {
        staticItemsNew.value[index].visible = val;
        labelChange(index);
      },
      setBtnDropDisableByCode(code, val) {
        const index = staticItemsNew.value.findIndex(item => item.code == code);
        if (index > -1) {
          staticItemsNew.value[index].disabled = val;
          labelChange(index);
        }
      },
      setBtnDropVisibleByCode(code, val) {
        const index = staticItemsNew.value.findIndex(item => item.code == code);
        if (index > -1) {
          staticItemsNew.value[index].visible = val;
          labelChange(index);
        }
      },
      width() {
        return refComponent.value.$el.clientWidth;
      },
      setBtnData(data) {
        staticItemsNew.value = cloneDeep(mappingProps.staticItems);
        i18nMethod();
        initData();
      },
    });
    let initLabel = mappingProps.label;
    const initLabel2 = mappingProps.label;
    let initSplit = mappingProps.split;
    let splitButtonTarget = null;

    let labelPosition = computed(() => {
      if ($q.platform.is.mobile) {
        return 'top';
      }
      return mappingProps.labelPosition;
    });
    let outWidth = computed(() => {
      if (mappingProps.showModel == 'auto' && mappingProps.maxWidth != '') {
        return `max-width:${mappingProps.maxWidth};`;
      }
      if (mappingProps.showModel == 'fixed' && mappingProps.fixedWidth != '') {
        return `width:${mappingProps.fixedWidth};`;
      }
    });

    if (mappingProps.popover) {
      mappingProps.split = false;
      mappingProps.label = '';
    }
    if (!mappingProps.dropdownIcon) {
      mappingProps.dropdownIcon = `${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowDown ?? 'icon-t-arrow-down'}`;
    }
    expose(mappingExpose);
    let initItems = cloneDeep(mappingProps.staticItems);
    const staticItemsNew = ref(cloneDeep(mappingProps.staticItems));
    //国际化处理
    const i18nMethod = () => {
      staticItemsNew.value.forEach((element, index) => {
        let initLabel = initItems[index].label;
        element.codeForClick = element.codeForClick
          ? element.codeForClick
          : initLabel;
      });

      if (!window.Funcs) {
        return;
      }
      for (let i of staticItemsNew.value) {
        if (i.hasOwnProperty('ValueInfo_label')) {
          i.label = Funcs.GetTerms(i.ValueInfo_label, i.label);
        }
      }
    };
    i18nMethod();
    watch(
      () => mappingProps.popover,
      (newVal, oldVal) => {
        if (newVal != oldVal) {
          mappingProps.split = newVal ? false : initSplit;
          mappingProps.label = newVal ? '' : initLabel;
        }
      },
    );
    watch(
      () => mappingProps.dropdownIcon,
      (newVal, oldVal) => {
        if (!newVal) {
          mappingProps.dropdownIcon = `${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowDown ?? 'icon-t-arrow-down'}`;
        }
      },
    );
    watch(
      () => mappingProps.split,
      (newVal, oldVal) => {
        if (!newVal && oldVal) {
          initSplit = newVal;
          mappingProps.label = initLabel;
        }
      },
    );
    watch(
      () => mappingProps.label,
      (newVal, oldVal) => {
        if (newVal != oldVal) {
          if (!mappingProps.popover) {
            mappingProps.label = newVal;
          }
          initLabel = mappingProps.label;
          if (mappingProps.split && mappingProps.dropdownWidth == 'fixed') {
            nextTick(() => {
              widthModel.value = `max-width:${refComponent.value.$el.clientWidth + 2}px;`;
            });
          }
        }
      },
    );
    watch(
      () => mappingProps.dropdownWidth,
      (newVal, oldVal) => {
        if (newVal == 'fixed') {
          nextTick(() => {
            widthModel.value = `max-width:${refComponent.value.$el.clientWidth + 2}px;`;
          });
        }
      },
    );
    const inDesign = ref(!!window['fas']?.inDesign); //判断是否设计时
    watch(
      () => {
        return mappingProps.staticItems;
      },
      (newVal, oldVal) => {
        if (
          (inDesign.value || mappingProps.needWatchStaticItems) &&
          JSON.stringify(newVal) != JSON.stringify(oldVal)
        ) {
          staticItemsNew.value = cloneDeep(mappingProps.staticItems);
          initItems = cloneDeep(mappingProps.staticItems);
          i18nMethod();
        }
      },
    );

    onMounted(() => {
      if (
        mappingProps.split &&
        staticItemsNew.value &&
        staticItemsNew.value.length > 0
      ) {
        let data = staticItemsNew.value.find(
          item => item.isDefaultBtn === true,
        );
        if (data) {
          mappingProps.label = data.label;
        }
      }
      // if (mappingProps.dropdownWidth == 'fixed') {
      //   nextTick(() => {
      //     widthModel.value = `max-width:${refComponent.value.$el.clientWidth + 2}px;`;
      //   })
      // }
    });
    function onClickHandler(params) {
      if (mappingProps.split) {
        let data = staticItemsNew.value.find(item => item.label == params);
        if (data) {
          let postData = cloneDeep(data);
          postData.codeInit = postData.code;
          postData.code = postData.codeForClick;
          emit('dropdown-item-click', toRaw(postData));
        }
      }
    }

    function itemClick(item, e) {
      if (item.disabled) {
        return;
      }
      if (mappingProps.split) {
        mappingProps.label = item.label;
      }
      let postData = cloneDeep(item);
      postData.codeInit = postData.code;
      postData.code = postData.codeForClick;
      emit('dropdown-item-click', postData);
      if (e) {
        e.stopPropagation();
        e.preventDefault();
        refComponent.value?.hide();
        return false;
      }
    }

    function labelChange(index) {
      if (
        mappingProps.split &&
        (mappingProps.label == staticItemsNew.value[index].label ||
          (mappingProps.label == '下拉按钮' &&
            mappingProps.label !== staticItemsNew.value[index].label))
      ) {
        let data = staticItemsNew.value.find(
          item => !item.disabled && item.visible,
        );
        if (data) {
          mappingProps.label = data.label;
        } else {
          mappingProps.label = '下拉按钮';
        }
      }
      if (
        staticItemsNew.value.every(
          item => item.hasOwnProperty('visible') && !item.visible,
        )
      ) {
        mappingProps.visible = false;
      } else {
        mappingProps.visible = true;
      }
    }

    return {
      mappingProps,
      attrs,
      labelPosition,
      refComponent,
      styles,
      pickOwnForBasicComponent,
      Component,
      onClickHandler,
      slots,
      itemClick,
      widthModel,
      outWidth,
      staticItemsNew,
    };
  },
});
</script>
